<?php

class Api{
    function get($req){
        $id = $req->param;
        $row = pt\db\Mysql::init()->row("select *,id as `key` from role where id = ?",$id);
        $row['permission'] = $row['permission'] ? json_decode($row['permission']) : array();
        $_row = get_role_permission();
        $row['permissionNodes'] = $_row['permissionNodes'];
        $row['permissionData'] = $_row['permissionData'];
        $row['permissionDataItems'] = $_row['permissionDataItems'];
        return $row;
    }
    function post($req){
        $name = $req->body->name;
        $notes = $req->body->notes;

        if(!$name || strlen($name) < 2){
            throw new ErrHttp("角色名至少2位",500);
        }
        $row = array(
            "name"=>$name,
            "notes"=>$notes,
            "permission"=>"{}",
            "add_time"=>date("Y-m-d H:is")
        );
        $id = pt\db\Mysql::init()->insert("role",$row);
        $res = array(
            "id"=>$id
        );
        return $res;
    }
    function put($req){
        $id = $req->param;
        $name = empty($req->body->name)?null:$req->body->name;
        $notes = empty($req->body->notes)?null:$req->body->notes;
        $permission = empty($req->body->permission)?null:$req->body->permission;
        $row = array();
        if($name){
            $row['name'] = $name;
        }
        if($notes){
            $row['notes'] = $notes;
        }
        if($permission){
            $row['permission'] = json_encode($permission);
        }

        pt\db\Mysql::init()->update("role",$row,array("id"=>$id));
        $res = array(
            "message"=>"修改成功"
        );
        return $res;
    }
    function delete($req){
        $id = $req->param;
        pt\db\Mysql::init()->delete("role",array("id"=>$id));
        $res = array(
            "message"=>"删除成功"
        );
        return $res;
    }
}
